﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Reflection;
using System.Configuration;
using System.ServiceModel.Configuration;
using Tencent.OA.App;

namespace Tencent.OA.ACM.Service
{
    /// <summary>
    /// 服务管理类。
    /// 用于启动/关闭所有的服务。
    /// </summary>
    public static class ServiceManager
    {
        private static List<ServiceHost> AllHosts = new List<ServiceHost>();

        /// <summary>
        /// 用ServiceHost Open服务，并添加到服务列表中。
        /// </summary>
        /// <param name="t">要Open的服务类型。</param>
        private static void OpenHost(Type t)
        {
            ServiceHost hst = new ServiceHost(t);
            hst.Open();
            AllHosts.Add(hst);
        }

        /// <summary>
        /// 从应用程序配置文件(app.config/web.config)启动所有system.serviceModel中的服务。
        /// </summary>
        public static void StartAllConfiguredServices()
        {
            Configuration conf = ConfigurationManager.OpenExeConfiguration(Assembly.GetEntryAssembly().Location);

            ServiceModelSectionGroup svcmod = (ServiceModelSectionGroup)conf.GetSectionGroup("system.serviceModel");
            foreach (ServiceElement el in svcmod.Services.Services)
            {
                Type svcType = Type.GetType(el.Name);
                if (svcType == null)
                {
                    string err = string.Format("Invalid Service Type [{0}] in configuration file.", el.Name);
                    try
                    {
                        LoggerProvider.CurrentLogger.Error(err);
                    }
                    catch { }
                    throw new Exception(err);
                }
                OpenHost(svcType);
                Console.WriteLine("Service starting :" + el.Name);
                try
                {
                    LoggerProvider.CurrentLogger.Error(string.Format("Service[{0}] started", el.Name));
                }
                catch { }
            }

        }


        public static void CloseAllServices()
        {
            foreach (ServiceHost hst in AllHosts)
            {
                hst.Close();
            }
        }
    }
}
